package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse res=(HttpServletResponse)response;
        String uri=req.getRequestURI();

        //System.out.println(uri+" uri start");
        //将获取的请求资源路径uri进行字符串切割处理
        String path=uri.substring(uri.lastIndexOf("/"));

        //System.out.println(path);
        if(path.equals("/loginServlet")||path.equals("/bootstrap.min.css")||path.equals("/jquery-2.1.0.min.js")||path.equals("/background.png")){
            chain.doFilter(request, response);
            return;
        }
        if(path.equals("/login.html")){
            chain.doFilter(request, response);
            return;
        }

        //System.out.println(uri+" uri fail");

        //获取session对象
        HttpSession session=req.getSession();
        //进行session验证
        Object obj=session.getAttribute("identity");
        String identity = String.valueOf(obj);

        if(identity.equals("null")){
            //跳转回登录页面
            res.sendRedirect("login.html");
            return;
        }

        if(identity.equals("student")&&(path.equals("/ratifyLessonListServlet")||path.equals("/disapprove.html"))){
            //跳转回登录页面
            res.sendRedirect("login.html");
            return;
        }

        if(identity.equals("administrator")&&path.equals("/lessonListServlet")){
            //跳转回登录页面
            res.sendRedirect("login.html");
            return;
        }

        if(identity.equals("teacher")&&path.equals("/lessonListServlet")){
            //跳转回登录页面
            res.sendRedirect("login.html");
            return;
        }
        chain.doFilter(request, response);
    }

}
